﻿using FDFtpSync.Core;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FDFtpSync.Ioc
{
    public class DefaultContainer : IContainer
    {
        private IServiceProvider _serviceProvider;
        private IServiceCollection _services;

        public DefaultContainer(IServiceCollection services = null)
        {
            _services = services ?? new ServiceCollection();
        }

        public IContainer Register(Action<IRegOptions> options)
        {
            var option = new DefaultRegOptions(_services);
            options?.Invoke(option);
            return this;
        }

        public IContainer Build()
        {
            _serviceProvider = _services.BuildServiceProvider();
            return this;
        }

        public T Resolve<T>()
        {
            Check();
            return _serviceProvider.GetService<T>();
        }

        public object Resolve(Type type)
        {
            Check();
            return _serviceProvider.GetService(type);
        }

        public IList<T> ResolveAll<T>()
        {
            Check();
            return _serviceProvider.GetServices<T>().ToList();
        }

        public IList<object> ResolveAll(Type type)
        {
            Check();
            return _serviceProvider.GetServices(type).ToList();
        }

        private void Check()
        {
            if (_serviceProvider == null)
                throw new InvalidProgramException("Should call the Build() after calling Register().");
        }
    }
}
